/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.listener;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;


public class BookmarkTabListener<T extends Fragment> implements TabListener {

    private Fragment fragment;
    private final Activity activity;
    private final Class<T> cls;
    private FragmentManager fragmentManager;
    private String tag;

    public BookmarkTabListener(Activity activity, Class<T> cls, FragmentManager fragmentManager, String tag) {
        this.activity = activity;
        this.cls = cls;
        this.fragmentManager = fragmentManager;
        this.tag = tag;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (fragment == null) {
            // try finding the fragment by it's tag
            fragment = fragmentManager.findFragmentByTag(tag);
        }

        if (fragment == null) {
            // If not, instantiate and add it to the activity
            fragment = Fragment.instantiate(activity, cls.getName());
            ft.add(android.R.id.content, fragment, tag);
        }
        else {
            // If it exists, simply attach it in order to show it
            ft.attach(fragment);
        }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (fragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(fragment);
        }
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }

}
